import { getHeatSourcePermisstion } from "@/api/heatSource";

const sourceList = sessionStorage.getItem("sourceList");

const state = {
    sidebar: {
        opened: sessionStorage.getItem("sidebarStatus") ?
            !!+sessionStorage.getItem("sidebarStatus") :
            true,
        withoutAnimation: false,
    },
    visitedViews: [],
    sourceData: sourceList ? JSON.parse(sourceList) : [],
};
const mutations = {
    TOGGLE_SIDEBAR: (state) => {
        state.sidebar.opened = !state.sidebar.opened;
        state.sidebar.withoutAnimation = false;
        if (state.sidebar.opened) {
            sessionStorage.setItem("sidebarStatus", 1);
        } else {
            sessionStorage.setItem("sidebarStatus", 0);
        }
    },
    // CLOSE_SIDEBAR: (state, withoutAnimation) => {
    //     sessionStorage.setItem("sidebarStatus", 0);
    //     state.sidebar.opened = false;
    //     state.sidebar.withoutAnimation = withoutAnimation;
    // },

    ADD_VISITED_VIEW: (state, visitedViews) => {
        state.visitedViews = visitedViews;
        // state.visitedViews.push(view)
    },
    DEL_VISITED_VIEW: (state, view) => {
        for (const [i, v] of state.visitedViews.entries()) {
            if (v.path === view.path) {
                state.visitedViews.splice(i, 1);
                break;
            }
        }
    },
    CLOSE_OTHERS_TAGS: (state, index) => {
        state.visitedViews.splice(index, 1);
    },
    DEL_ALL_VISITED_VIEWS: (state) => {
        const affixTags = state.visitedViews.filter((tag) => tag.meta.affix);
        state.visitedViews = affixTags;
    },
    SET_HEATSOURCE: (state, sourceData) => {
        sessionStorage.setItem("sourceList", JSON.stringify(sourceData));
        state.sourceData = sourceData;
    },
};

const actions = {
    GET_SOURCEData({ commit }, userId) {
        getHeatSourcePermisstion({ userId }).then((res) => {
            if (res.data.success) {
                let list = res.data.data;
                const result = list.map((item) => {
                    return { label: item.name, value: item.id };
                });
                commit("SET_HEATSOURCE", result);
            }
        });
    },
    toggleSideBar({ commit }) {
        commit("TOGGLE_SIDEBAR");
    },
    closeSideBar({ commit }, { withoutAnimation }) {
        commit("CLOSE_SIDEBAR", withoutAnimation);
    },
    toggleDevice({ commit }, device) {
        commit("TOGGLE_DEVICE", device);
    },
    addView({ commit }, view) {
        commit("ADD_VISITED_VIEW", view);
    },
    delView({ commit, state }, view) {
        return new Promise((resolve) => {
            commit("DEL_VISITED_VIEW", view);
            resolve(state.visitedViews);
        });
    },
    closeOthersTags({ commit }, index) {
        commit("CLOSE_OTHERS_TAGS", index);
    },
    delAllViews({ commit }) {
        commit("DEL_ALL_VISITED_VIEWS");
    },
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
};